package org.unique.weibooauthtest.activity;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.SortedSet;

import android.util.Log;

import oauth.signpost.OAuthConsumer;
import oauth.signpost.OAuthProvider;
import oauth.signpost.basic.DefaultOAuthConsumer;
import oauth.signpost.basic.DefaultOAuthProvider;
import oauth.signpost.commonshttp.CommonsHttpOAuthConsumer;
import oauth.signpost.exception.OAuthCommunicationException;
import oauth.signpost.exception.OAuthExpectationFailedException;
import oauth.signpost.exception.OAuthMessageSignerException;
import oauth.signpost.exception.OAuthNotAuthorizedException;
import oauth.signpost.http.HttpParameters;

public class OAuth {
	public static OAuth oAuth;
	private Config config;
	public OAuthProvider httpOauthprovider;
	public CommonsHttpOAuthConsumer httpOauthConsumer;

	public OAuth() {
		// TODO Auto-generated constructor stub
		config = Config.getInstance();
		httpOauthConsumer = new CommonsHttpOAuthConsumer(config.consumerKey,
				config.consumerSecret);
		httpOauthprovider = new DefaultOAuthProvider(
				config.requestTokenEndpointUrl, config.accessTokenEndpointUrl,
				config.authorizationWebsiteUrl);
	}

	public static OAuth getInstance() {
		if (oAuth == null) {
			oAuth = new OAuth();
		}
		return oAuth;
	}

	/**
	 * 获取request token
	 * 
	 * @return requestToken
	 */
	public String getRequestToken() {
		String requestToken = "";

		try {
			requestToken = httpOauthprovider.retrieveRequestToken(
					httpOauthConsumer, config.callBackUrl);
		} catch (OAuthMessageSignerException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (OAuthNotAuthorizedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (OAuthExpectationFailedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (OAuthCommunicationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return requestToken;
	}

	public String getAccessToken(String verifier) {
		String accessToken = "";
		try {
			httpOauthprovider.setOAuth10a(true);
			httpOauthprovider.retrieveAccessToken(httpOauthConsumer, verifier);
		} catch (OAuthMessageSignerException ex) {
			ex.printStackTrace();
		} catch (OAuthNotAuthorizedException ex) {
			ex.printStackTrace();
		} catch (OAuthExpectationFailedException ex) {
			ex.printStackTrace();
		} catch (OAuthCommunicationException ex) {
			ex.printStackTrace();
		}
		return accessToken;
	}

	public String getUsetId() {
		SortedSet<String> user_id = httpOauthprovider.getResponseParameters()
				.get("user_id");
		return user_id.first();
	}

	public String getOAuthToken() {
		return httpOauthConsumer.getToken();
	}

	public String getOAuthTokenSecret() {
		return httpOauthConsumer.getTokenSecret();
	}

	public void share2weibo(String accessToken, String tokenSecret,
			String status, String picPath) {
		Log.i("weibo_status", status);
		
		OAuthConsumer consumer = new DefaultOAuthConsumer(config.consumerKey,
				config.consumerSecret);
		consumer.setTokenWithSecret(accessToken, tokenSecret);
		URL url = null;
		HttpURLConnection request;
		try {
			status = URLEncoder.encode(status, "utf-8").replaceAll(
					"\\+", "%20");
		} catch (UnsupportedEncodingException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		/* 没有图片时发送纯文字微薄 */
		if (picPath == null) {
			try {
				url = new URL("http://api.t.sina.com.cn/statuses/update.json");
				request = (HttpURLConnection) url.openConnection();
				request.setDoOutput(true);
				request.setRequestMethod("POST");
				HttpParameters para = new HttpParameters();
				para.put("status", status);
				consumer.setAdditionalParameters(para);
				consumer.sign(request);
				OutputStream ot = request.getOutputStream();
				ot.write(("status=" +URLEncoder.encode(status,"utf-8")).replaceAll("\\+", "%20").getBytes());
				ot.flush();
				ot.close();
				Log.i("update", "Sending request...");
				request.connect();
				Log.i("Response",
						request.getResponseCode() + " "
								+ request.getResponseMessage());
				BufferedReader reader = new BufferedReader(
						new InputStreamReader(request.getInputStream()));
				String b = null;
				while ((b = reader.readLine()) != null) {
					Log.i("inputStream", b);
				}
			} catch (Exception e) {
				// TODO: handle exception
			}
			/* 有图片 */
		} else {
			Log.i("weibo_picPath", picPath);
			Log.i("upload", "begin");
			try {
				url = new URL("http://api.t.sina.com.cn/statuses/upload.json");
				request = (HttpURLConnection) url.openConnection();
				request.setDoOutput(true);
				request.setRequestMethod("POST");
				HttpParameters para = new HttpParameters();
				para.put("status", status);
				String boundary = "---------------------------37531613912423";
				String content = "--"
						+ boundary
						+ "\r\nContent-Disposition: form-data; name=\"status\"\r\n\r\n";
				String pic = "\r\n--"
						+ boundary
						+ "\r\nContent-Disposition: form-data; name=\"pic\"; filename=\"postpic.jpg\"\r\nContent-Type: image/jpeg\r\n\r\n";
				byte[] end_data = ("\r\n--" + boundary + "--\r\n").getBytes();
				File f = new File(picPath);
				FileInputStream stream = new FileInputStream(f);
				byte[] file = new byte[(int) f.length()];
				stream.read(file);
				request.setRequestProperty("Content-Type",
						"multipart/form-data; boundary=" + boundary); // 设置表单类型和分隔符
				request.setRequestProperty(
						"Content-Length",
						String.valueOf(content.getBytes().length
								+ status.getBytes().length
								+ pic.getBytes().length + f.length()
								+ end_data.length)); // 设置内容长度
				Log.i("setRequestProperty_Content-Length", String.valueOf(content.getBytes().length
								+ status.getBytes().length
								+ pic.getBytes().length + f.length()
								+ end_data.length));
				consumer.setAdditionalParameters(para);
				consumer.sign(request);
				OutputStream ot = request.getOutputStream();
				ot.write(content.getBytes());
				ot.write(status.getBytes());
				ot.write(pic.getBytes());
				ot.write(file);
				ot.write(end_data);
				ot.flush();
				ot.close();
				Log.i("upload", "Sending request...");
				request.connect();
				Log.i("Response",
						request.getResponseCode() + " "
								+ request.getResponseMessage());
				BufferedReader reader = new BufferedReader(
						new InputStreamReader(request.getInputStream()));
				String b = null;
				while ((b = reader.readLine()) != null) {
					Log.i("inputStream", b);
				}
			} catch (Exception e) {
				//TODO: handle exception
				Log.e("error share", e.getMessage());
			}
		}
	}
}
